# -*- coding: UTF-8 -*-
"""
    截图
    @Project ：game_chat_monitor
    @File ：game_snapshot.py
    @Author ：lc
    @Date ：2022.8.31 17:07
"""
import datetime

import numpy
from PIL import Image
from airtest.cli.parser import cli_setup
from airtest.core.api import *
from airtest.aircv import *
from pytesseract import pytesseract

from config import GAME_LANGUAGE, GAME_NAME, CHAT_UPPER_LEFT, CHAT_LOWER_RIGHT

text_content = ""


def connect_game_device():
    """
    连接设备
    :return:
    """
    if not cli_setup():
        connect_device("Android:///")
    auto_setup(__file__)


def screen_snapshot():
    """
    屏幕截图保存
    :return:
    """
    screen_file_name = r"gamescreen.jpg"
    # image_path_name = f"./img/{str(time.time())[:10]}.jpg"
    screen = G.DEVICE.snapshot()
    print("截图对象返回值：", screen)
    count = 0
    while 1:
        if screen is not None:
            print("有图像了豁")
            break
        screen = G.DEVICE.snapshot()
        count += 1
        print(f"没有截到图，再次尝试第{count}次")
    try:
        screen_save = aircv.crop_image(screen, (*CHAT_UPPER_LEFT, *CHAT_LOWER_RIGHT))
    except Exception as e:
        print("保存图片时没有shape属性", e)
    image = cv2_2_pil(screen_save)
    image.save(screen_file_name, quality=99, optimize=True)


def tesseract_ocr():
    """
    图像识别
    :return:识别的文字
    """
    # image = Image.open(r"game_screen.jpg")
    # image = cv2.imread(r"game_screen.jpg")
    try:
        image = cv2.imdecode(numpy.fromfile(r"gamescreen.jpg", dtype=numpy.uint8), -1)
        print("读取到的图像：", image.shape)
    except Exception as e:
        print("没有读取到图像的shape", e)
    if GAME_LANGUAGE == "中文":
        image_text = pytesseract.image_to_string(image, lang="chi_sim")
    else:
        image_text = pytesseract.image_to_string(image)
    return image_text


def save_orc_text():
    """
    存储文本
    :return:
    """
    text_content = tesseract_ocr()
    print("识别到的文本是：" + '\n', text_content)
    if len(text_content.replace(" ", "").replace("\n", "")):
        file_name = GAME_NAME
        game_time = "当前时间：" + str(datetime.datetime.now())
        if GAME_LANGUAGE == "中文":
            file = open(f"{file_name}.txt", "a", encoding="utf8")
        else:
            file = open(f"{file_name}.txt", "a")
        file.writelines(game_time + '\n')
        file.writelines(text_content + '\n')
        file.close()


def judge_text():
    """
    判断是否获取重复文本
    :return:
    """
    global text_content
    if text_content != tesseract_ocr():
        text_content = tesseract_ocr()
        return text_content
    else:
        return False


if __name__ == "__main__":
    print(str(time.time())[:10])
